package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.core.SeckillKey;
import com.dongdongshop.mapper.TbSeckillGoodsMapper;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbSeckillGoodsExample;
import com.dongdongshop.service.SeckillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Component
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private TbSeckillGoodsMapper seckillGoodsMapper;

    @Override
    public List<TbSeckillGoods> getSeckillGoodsInfo() {
        //先查缓存，缓存中没有，再查数据库
        List<TbSeckillGoods> seckillList =redisTemplate.boundHashOps(SeckillKey.SECKILLGOODS_KEY).values();
        if (null == seckillList||seckillList.size() <= 0){
            //查询条件
            TbSeckillGoodsExample example = new TbSeckillGoodsExample();
            TbSeckillGoodsExample.Criteria criteria = example.createCriteria();
            //查询通过审核的商品
            criteria.andStatusEqualTo("1");
            criteria.andStartTimeLessThanOrEqualTo(new Date());//开始时间小于等于当前时间
            criteria.andEndTimeGreaterThanOrEqualTo(new Date());//结束时间大于等于当前时间
            criteria.andStockCountGreaterThan(0);//剩余库存
            seckillList = seckillGoodsMapper.selectByExample(example);
            //遍历集合，将列表数据一个一个放到缓存中
            for (TbSeckillGoods goods : seckillList) {
                redisTemplate.boundHashOps(SeckillKey.SECKILLGOODS_KEY).put(goods.getId(),goods);
                //将商品库存1存放到缓存
                redisTemplate.boundValueOps(goods.getId()).set(goods.getStockCount().toString());
            }

        }
        return seckillList;
    }

    @Override
    public TbSeckillGoods findSeckillGoods(Long id) {
        TbSeckillGoods seckillList = (TbSeckillGoods)redisTemplate.boundHashOps(SeckillKey.SECKILLGOODS_KEY).get(id);

        return seckillList;
    }
}
